﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace VTLive.Models
{
    public class ScheduleRepository
    {
        VTliveDataContext db = new VTliveDataContext();

        public Schedule GetLatestScheduleOfStation(int stationID)
        {
            Schedule result =(from Schedule schedule in db.Schedules 
                              where schedule.StationID == stationID && schedule.Confirmed 
                              select schedule).FirstOrDefault();
            if(result != null) return result;
            else
            {
                Schedule Result = new Schedule();
                Result.Confirmed = false;
                //Result.StartTime = DateTime.Now;
                Result.StationID = stationID;
                
                return Result;
            }
        }

        public Schedule GetCurrentScheduleOfStation(int stationID)
        {
            Schedule result = (from Schedule schedule in db.Schedules
                               where schedule.StationID == stationID && schedule.StartTime.Year == DateTime.Now.Year && schedule.StartTime.DayOfYear == DateTime.Now.DayOfYear
                               select schedule).FirstOrDefault();
            if (result != null) return result;
            else
            {
                Schedule Result = new Schedule();
                Result.Confirmed = false;
                //Result.StartTime = DateTime.Now;
                Result.StationID = stationID;

                return Result;
            }
        }


        public IQueryable<Schedule> GetAllSchedules()
        {
            return db.Schedules;
        }

        public Schedule GetSchedule (int ScheduleID)
        {
            return db.Schedules.SingleOrDefault(s => s.ID == ScheduleID);
        }

        public void Add(Schedule MySchedule)
        {
            db.Schedules.InsertOnSubmit(MySchedule);
        }

        public void Delete(Schedule MySchedule)
        {
            db.Schedules.DeleteOnSubmit(MySchedule);
        }

        public void Save()
        {
            db.SubmitChanges();
        }

        internal IEnumerable<Schedule> GetAllSchedulesOfStation(int p)
        {
            return (from schedule in db.Schedules
                    where schedule.StationID == p
                    select schedule);
        }
    }
}
